import { useState } from "react";
import { Button, Alert } from "antd";

import { registerTokenAuth, register } from "../utils/api";
import { base64ToUint8Array, arrayBufferToBase64 } from "../utils/utils";

const Profile = () => {
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState(null);

  const registerToken = async (startRegistrationEndpoint) => {
    setBusy(true);
    try {
      const response = await registerTokenAuth(startRegistrationEndpoint);
      setMessage("Send response");

      const publicKey = {
        ...response,
        challenge: base64ToUint8Array(response.challenge),
        user: {
          ...response.user,
          id: base64ToUint8Array(response.user.id),
        },
      };

      console.log("publicKey:", publicKey);

      const attestation = await navigator.credentials.create({ publicKey });
      setMessage("Create attestation");

      const attestationObject = {
        id: attestation.id,
        rawId: arrayBufferToBase64(attestation.rawId),
        response: {
          clientDataJSON: arrayBufferToBase64(
            attestation.response.clientDataJSON
          ),
          attestationObject: arrayBufferToBase64(
            attestation.response.attestationObject
          ),
        },
        type: attestation.type,
      };

      console.log("attestationObject:", attestationObject);

      const attestationResponse = await register(attestationObject);
      setMessage("registered!");

      if (attestationResponse && attestationResponse.verified) {
        alert("New key registered");
      }
    } catch (err) {
      console.error("Error during registration:", err);
      setMessage("" + err);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div>
      <h1>Profile</h1>
      <p>Register new hardware key</p>
      <div className="button-wrapper">
        <Button
          block
          disabled={busy}
          onClick={() => registerToken("/startRegister")}
        >
          Enable log in by physical key
        </Button>
        <Button
          block
          disabled={busy}
          onClick={() => registerToken("/startFingerprint")}
        >
          Enable log in by fingerprint
        </Button>
      </div>
      {message && <Alert className="alert" banner message={message} />}
    </div>
  );
};

export default Profile;
